/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.whosly.disclosure.early.handler;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import com.google.gson.JsonObject;
import com.whosly.disclosure.early.handler.enums.DingtalkMsgType;
import com.whosly.disclosure.early.handler.infra.json.GsonFactory;
import com.whosly.disclosure.early.handler.param.ITextParam;
import com.whosly.disclosure.early.handler.param.TextParam;
import com.whosly.disclosure.early.handler.spi.ErrorHandler;
import com.whosly.disclosure.early.handler.spi.exception.ConfigurationException;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Collections;

/**
 * error handler for dingtalk error message.
 *
 * SPI 加载
 */
@Slf4j
public final class DingtalkErrorHandler implements ErrorHandler {

    /**
     * config.yaml  property 的前缀
     */
    public static final String CONFIG_YAML_PREFIX = "dingtalk";

    /**
     * application.yml  property 的前缀
     */
    public static final String CONFIG_YML_PREFIX = "spring.whosly.disclosure.dingtalk";

    /**
     * 配置文件地址
     */
    public static final String ERROR_HANDLER_CONFIG = "conf/error-handler-dingtalk.yaml";

    @Setter
    private DingtalkProperties dingtalkProperties;
    
    private final CloseableHttpClient httpclient = HttpClients.createDefault();

    public DingtalkErrorHandler() {
        registerShutdownHook();
    }

    public DingtalkErrorHandler(DingtalkProperties dingtalkConfig) {
        this.dingtalkProperties = dingtalkConfig;

        registerShutdownHook();
    }
    
    @Override
    public void handleException(final String name, final Throwable cause) {
        // check
        if(dingtalkProperties == null || StringUtils.isEmpty(dingtalkProperties.getWebhook())){
            log.warn("无 dingtalkProperties 配置信息。 ignore.");
            return;
        }

        String paramJson = getParamJson(getMsg(name, cause), dingtalkProperties);

        sender(name, paramJson, cause);
    }

    @Override
    public void handleMsg(String name, String message) {
        // check
        if(dingtalkProperties == null || StringUtils.isEmpty(dingtalkProperties.getWebhook())){
            log.warn("无 dingtalkProperties 配置信息。 ignore.");
            return;
        }

        String paramJson = getParamJson(getMsg(name, message), dingtalkProperties);

        sender(name, paramJson, message);
    }

    /**
     * 发送消息
     *
     * @param paramJson
     */
    private void sender(String jobName, String paramJson, Object cause) {
        // 异步处理。加入线程池

        HttpPost httpPost = new HttpPost(getUrl());
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(dingtalkProperties.getConnectTimeout())
                .setSocketTimeout(dingtalkProperties.getReadTimeout()).build();
        httpPost.setConfig(requestConfig);

        StringEntity entity = new StringEntity(paramJson, StandardCharsets.UTF_8);
        entity.setContentEncoding(StandardCharsets.UTF_8.name());
        entity.setContentType("application/json");
        //entity.setContentType(MediaType.JSON_UTF_8.toString());
        httpPost.setEntity(entity);
        try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
            int status = response.getStatusLine().getStatusCode();
            if (HttpURLConnection.HTTP_OK == status) {
                JsonObject resp = GsonFactory.getGson().fromJson(EntityUtils.toString(response.getEntity()), JsonObject.class);
                if (!"0".equals(resp.get("errcode").getAsString())) {
                    log.error("An exception has occurred '{}', But failed to send alert by Dingtalk because of: {}", jobName, resp.get("errmsg").getAsString(), cause);
                } else {
                    // 发送成功
                    log.debug("An exception has occurred '{}', Notification to Dingtalk was successful.", jobName, cause);
//                    log.info("An exception has occurred '{}', Notification to Dingtalk was successful.", jobName, cause);
                }
            } else {
                log.error("An exception has occurred '{}', But failed to send alert by Dingtalk because of: Unexpected response status: {}", jobName, status, cause);
            }
        } catch (IOException ex) {
            log.error("An exception has occurred '{}', But failed to send alert by Dingtalk because of", jobName, ex);
        }
    }

    /**
     *
     * @param msg  发送的内容
     * @return
     */
    private String getParamJson(final String msg, DingtalkProperties dingtalkProperties) {
        // 取消息类型
        DingtalkMsgType dingtalkMsgType = DingtalkMsgType.of(dingtalkProperties.getMsgtype());
        if(dingtalkMsgType == null){
            dingtalkMsgType = DingtalkMsgType.TEXT;
        }

        // 区分取 dingtalkMsgType
        TextParam.At at = new TextParam.At();

        String mobiles = dingtalkProperties.getSysOwenerPhone();
        if(StringUtils.isNotEmpty(mobiles)){
            at.setAtMobiles(Sets.newHashSet(Splitter.on(",")
                    .trimResults().omitEmptyStrings()
                    .splitToList(mobiles)));
        }

        ITextParam textParam = TextParam.builder()
                .text(Collections.singletonMap("content", msg))
                .at(at)
                .build();
        return GsonFactory.getGson().toJson(textParam);
//        return textParam;

//        return GsonFactory.getGson().toJson(
//                ImmutableMap.of("msgtype", "text",
//                        "text", Collections.singletonMap("content", msg)));
    }
    
    private String getMsg(final String jobName, final Throwable cause) {
        StringWriter sw = new StringWriter();
        cause.printStackTrace(new PrintWriter(sw, true));
        String msg = String.format("'%s' exception occur  processing, caused by %s", jobName, sw.toString());

        if (!Strings.isNullOrEmpty(dingtalkProperties.getKeyword())) {
            msg = dingtalkProperties.getKeyword().concat("：").concat(msg);
        }

        return msg;
    }

    private String getMsg(final String jobName, final String cause) {
        String msg = String.format("'%s' exception occur  processing, caused by %s", jobName, cause);

        if (!Strings.isNullOrEmpty(dingtalkProperties.getKeyword())) {
            msg = dingtalkProperties.getKeyword().concat("：").concat(msg);
        }

        return msg;
    }
    
    private String getUrl() {
        if (Strings.isNullOrEmpty(dingtalkProperties.getSecret())) {
            return dingtalkProperties.getWebhook();
        } else {
            return getSignUrl();
        }
    }
    
    private String getSignUrl() {
        try {
            Long timestamp = System.currentTimeMillis();
            return String.format("%s&timestamp=%s&sign=%s", dingtalkProperties.getWebhook(), timestamp, sign(timestamp));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException ex) {
            throw new ConfigurationException(ex);
        }
    }
    
    private String sign(final Long timestamp) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        String stringToSign = timestamp + "\n" + dingtalkProperties.getSecret();
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(dingtalkProperties.getSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        return URLEncoder.encode(new String(Base64.getEncoder().encode(signData)), StandardCharsets.UTF_8.name());
    }
    
    @Override
    public String getType() {
        return "DINGTALK";
    }
    
    private void registerShutdownHook() {
        Thread t = new Thread("DingtalkErrorHandler Shutdown-Hook") {
            @SneakyThrows
            @Override
            public void run() {
                log.info("Shutting down httpclient...");
                httpclient.close();
            }
        };
        Runtime.getRuntime().addShutdownHook(t);
    }
}
